package com.thinkgem.jeesite.modules.front.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.apache.shiro.session.Session;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.support.json.JSONUtils;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.thinkgem.jeesite.modules.front.entity.FrontUser;
import com.thinkgem.jeesite.modules.front.entity.MyTheme;
import com.thinkgem.jeesite.modules.front.entity.TestRecord;
import com.thinkgem.jeesite.modules.front.entity.TestResult;
import com.thinkgem.jeesite.modules.front.service.TestRecordService;
import com.thinkgem.jeesite.modules.front.service.TestResultService;
public class TestRecordUtils {
	
	private static TestRecordService testRecordService = SpringContextHolder.getBean(TestRecordService.class);
	private static TestResultService testResultService = SpringContextHolder.getBean(TestResultService.class);
	/**
	 * 保存用户测试结果详细记录
	 * @param record 序号-ID-具体选项-用户回答  以|隔开的结果集
	 * @param type 1 兴趣测试2性格测试
	 */
	@Transactional(readOnly = false)
	public static void saveThemeTestRecord(String record,FrontUser frontUser,String type){
		String[] records = record.split("\\|");
		List<TestRecord> testRecordList = new ArrayList<>();
		for (String re : records) {
			String[] oneRecord = re.split("-");
			TestRecord testRecord = new TestRecord();
			//题目ID
			MyTheme myTheme = new MyTheme();
			myTheme.setId(oneRecord[1]);
			testRecord.setTheme(myTheme);
			
			//测试时间
			testRecord.setTestDate(new Date());
			
			//用户
			testRecord.setFrontUser(frontUser);
			
			//测试类型1  兴趣测试2性格测试
			testRecord.setTestType(type);
			
			
			TestRecord oldTestRecord = testRecordService.getByUserIdAndThemeId(testRecord);
			//如果没有查询到此题目的记录则新增记录        查询到老记录则更新记录
			if(oldTestRecord == null){
				testRecord.setIsNewRecord(true);
				testRecord.setId(IdGen.uuid());
			}else{
				//如果有老记录那么执行跟新
				testRecord.setId(oldTestRecord.getId());
			}
			//序号
			testRecord.setSquence(oneRecord[0]);
			testRecord.setAnswer(oneRecord[2]);
			testRecord.setScore(oneRecord[3]);
			testRecordList.add(testRecord);
		}
		for (TestRecord testRecord : testRecordList) {
			testRecordService.save(testRecord);
		}
	}
	/**
	 * 查询当前用户该题目答题记录
	 */
	public static TestRecord getByUserIdAndThemeId(String themeId,String type){
		TestRecord testRecord = new TestRecord();
		
		Session session = FrontUserUtils.getSession();
		FrontUser frontUser = (FrontUser)session.getAttribute(FrontUserUtils.FRONT_USER_INFO);
		testRecord.setFrontUser(frontUser);
		
		MyTheme myTheme = new MyTheme();
		myTheme.setId(themeId);
		testRecord.setTheme(myTheme);
		//测试类型
		testRecord.setTestType(type);

		return testRecordService.getByUserIdAndThemeId(testRecord);
	}
	/**
	 * 生成兴趣测试报告
	 */
	public static TestResult createInReport() {
		TestRecord testRecord = new TestRecord();
		
		Session session = FrontUserUtils.getSession();
		FrontUser frontUser = (FrontUser)session.getAttribute(FrontUserUtils.FRONT_USER_INFO);
		testRecord.setFrontUser(frontUser);
		//测试类型
		testRecord.setTestType("1");
		List<TestRecord> recordList = testRecordService.findList(testRecord);
		Map<String, Integer> map = new TreeMap<String,Integer>();
		for (TestRecord re : recordList) {
			String score = re.getScore();
			if("0".equals(score)){
				continue;
			}
			if(map.containsKey(score)){
				map.put(score, map.get(score)+1);
			}else{
				map.put(score, 1);
			}
		}
		//补全 类型一个都没有的补为0
		String[] keys = {"R","I","A","S","E","C"};
		for (String key : keys) {
			if(!map.containsKey(key)){
				map.put(key, 0);
			}
		}
        
		//得到成绩前三的类型
        //将map.entrySet()转换成list
        List<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
        //通过比较器来实现排序
        Collections.sort(list,new Comparator<Map.Entry<String,Integer>>() {
            //降序排序
            public int compare(Entry<String, Integer> o1,
                    Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
            
        });

        Integer max = list.get(0).getValue();
        //取得分最高的类型 得分相同全选
        StringBuilder sb = new StringBuilder();
        for(Map.Entry<String,Integer> mapping:list){ 
        	if(mapping.getValue() == max){
        		sb.append(mapping.getKey()+",");
        	}
        }
        String resultType = sb.toString();
        resultType = resultType.substring(0, resultType.length()-1);
		String score = JSONUtils.toJSONString(map);
		
		
		//保存测试结果
		TestResult testResult = new TestResult();
		testResult.setFrontUser(frontUser);
		//设置测试结果类型
		testResult.setResultType(resultType);
		//测试类型(1:兴趣测试，2：性格测试）
		testResult.setExmaType("1");
		//各个类型得分情况  生成蜘蛛图需要
		testResult.setScore(score);
		testResultService.save(testResult);
		return testResult;
	}
	/**
	 * 生成性格测试报告
	 */
	public static TestResult createMbtiReport() {
		TestRecord testRecord = new TestRecord();
		
		Session session = FrontUserUtils.getSession();
		FrontUser frontUser = (FrontUser)session.getAttribute(FrontUserUtils.FRONT_USER_INFO);
		testRecord.setFrontUser(frontUser);
		//测试类型
		testRecord.setTestType("2");
		List<TestRecord> recordList = testRecordService.findList(testRecord);
		Map<String, Integer> map = new TreeMap<String,Integer>();
		for (TestRecord re : recordList) {
			String score = re.getScore();
			if(map.containsKey(score)){
				map.put(score, map.get(score)+1);
			}else{
				map.put(score, 1);
			}
		}
		//补全 类型一个都没有的补为0
		String[] keys = {"E","S","T","J","I","N","F","P"};
		for (String key : keys) {
			if(!map.containsKey(key)){
				map.put(key, 0);
			}
		}
		//类型规则参见 职业测评-详细功能描述.doc
        StringBuilder sb = new StringBuilder();
        if(map.get("E") <= map.get("I")){
        	sb.append("I,");
        }else{
        	sb.append("E,");
        }
        if(map.get("S") <= map.get("N")){
        	sb.append("N,");
        }else{
        	sb.append("S,");
        }
        if(map.get("T") <= map.get("F")){
        	sb.append("F,");
        }else{
        	sb.append("T,");
        }
        if(map.get("J") <= map.get("P")){
        	sb.append("P,");
        }else{
        	sb.append("J,");
        }
        
        String resultType = sb.toString();
        resultType = resultType.substring(0, resultType.length()-1);
		String score = JSONUtils.toJSONString(map);
		
		//保存测试结果
		TestResult testResult = new TestResult();
		testResult.setFrontUser(frontUser);
		//设置测试结果类型
		testResult.setResultType(resultType);
		//测试类型(1:兴趣测试，2：性格测试）
		testResult.setExmaType("2");
		//各个类型得分情况  生成蜘蛛图需要
		testResult.setScore(score);
		testResultService.save(testResult);
		
		//生成测试报告删除本次测试详细记录
		testRecordService.deleteRecordByUserAndType(testRecord);
		
		return testResult;
	}
	
}
